package com.njupt.yanglonglong.report.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.njupt.yanglonglong.report.demo.common.Result;
import com.njupt.yanglonglong.report.demo.entity.RUser;
import com.njupt.yanglonglong.report.demo.entity.TeamReport;
import com.njupt.yanglonglong.report.demo.service.TeamReportService;
import com.njupt.yanglonglong.report.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author yangllong
 * @Date 2021/5/29 21:20
 */
@RestController
@Slf4j
@CrossOrigin
public class TeamReportController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TeamReportService teamReportService;

    /**
     * 获取团队报告
     *
     * @param request token
     * @param map     team experId
     * @return TeamReport
     */
    @PostMapping("/getTeamReportByTeamIdAndExperId")
    public Result getTeamReportByTeamIdAndExperId(HttpServletRequest request,
                                                  @RequestBody HashMap<String, String> map) {
        JSONObject res = new JSONObject();
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            return Result.unauthorized();
        }
        String team = map.get("teamIds");
        String experId = map.get("experId");
        log.info("/getTeamReportByTeamIdAndExperId: teamIds:" + team + ", experId=" + experId);
        TeamReport teamReport = teamReportService.getTeamReportByTeamIdAndExperId(team, experId);
        res.put("teamReport", teamReport);
        res.put("msg", "获取报告信息成功");
        return Result.success(res);
    }

    /**
     * 协同编辑
     *
     * @param request token
     * @param map     experId teamIds
     * @return 101 无人编辑
     * 102 有人编辑
     * 103 本人编辑
     */
    @PostMapping("/editTeamReport")
    public Result editTeamReportByTeamIdAndExperId(HttpServletRequest request,
                                                   @RequestBody HashMap<String, String> map) {
        Result result = new Result();
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            return Result.unauthorized();
        }
        String team = map.get("teamIds");
        String experId = map.get("experId");
        log.info("/editTeamReport: teamIds:" + team + ", experId=" + experId);
        String key = experId + "_" + team;
        String editUserId = redisUtil.getIsLocked(key);
        if (editUserId == null) {
            result.setStatus(101);
            result.setMessage("当前无人编辑");
            redisUtil.lockReport(key, user.getUserId());
            return result;
        } else if (editUserId.equals(user.getUserId())) {
            result.setStatus(103);
            result.setMessage("当前您正在编辑编辑");
            return result;
        }
        result.setStatus(102);
        result.setMessage("当前" + editUserId + "正在编辑，请稍后再试");
        return result;
    }

    /**
     * 提交团队报告，解锁，其他人可编辑
     *
     * @param request    token
     * @param teamReport teamReport
     * @return success
     */
    @PostMapping("/submitTeamReport")
    public Result submitTeamReport(HttpServletRequest request, @RequestBody TeamReport teamReport) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            return Result.unauthorized();
        }
        String key = teamReport.getExperId() + "_" + teamReport.getTeamIds();
        String realEditor = redisUtil.getIsLocked(key);
        if (!realEditor.equals(user.getUserId())) {
            Result result = new Result();
            result.setStatus(201);
            result.setMessage("当前" + realEditor + "正在编辑请稍后提交");
            return result;
        }
        try {
            redisUtil.unlockReport(key);
            teamReport.setStatus(2);
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            teamReport.setReportTime(sdf.format(now));
            teamReportService.saveOrUpdate(teamReport);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("报告提交失败");
        }
        return Result.success("报告提交成功");
    }
}
